package org.hxzon.rpggame.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hxzon.rpggame.consts.FieldConsts;
import org.hxzon.util.Data;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

//初始定义
public class Def extends Data {

    private JSONObject def;

    public Def(JSONObject def) {
        super(new HashMap<String, Object>());
        this.def = def;
        importDef();
    }

    public String getDid() {
        return getString(FieldConsts.GoDid, null);
    }

    //不支持修改性操作
    @Override
    public Object put(String key, Object o) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Object putTmp(String key, Object o) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void putAll(Map<String, ?> m) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void putAllTmp(Map<String, ?> m) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Object remove(String key) {
        throw new UnsupportedOperationException();
    }

    @Override
    public void clear() {
        throw new UnsupportedOperationException();
    }

    //
    private void importDef() {
        for (String key : def.keySet()) {
            super.put(key, convert(def.get(key)));
        }
    }

    private Object convert(Object o) {
        if (o instanceof JSONObject) {
            return toMap((JSONObject) o);
        } else if (o instanceof JSONArray) {
            return toList((JSONArray) o);
        }
        return o;
    }

    private Map<String, Object> toMap(JSONObject o) {
        Map<String, Object> map = new HashMap<String, Object>();
        for (String key : o.keySet()) {
            map.put(key, convert(o.get(key)));
        }
        return map;
    }

    private List<Object> toList(JSONArray o) {
        List<Object> list = new ArrayList<Object>();
        for (Object e : o) {
            list.add(convert(e));
        }
        return list;
    }

}
